package jee.boot.oauth.standard.delegated;

import com.google.common.collect.Lists;
import jee.boot.common.basic.Page;
import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.remote.RemoteEndpoint;
import jee.boot.common.standard.AccountHandler;
import jee.boot.common.standard.AuthorityHandler;
import jee.boot.common.utils.JsonMapper;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.auth.*;
import jee.boot.entity.task.IexpTaskConfig;
import jee.boot.entity.task.IexpTask;
import jee.boot.entity.task.ExportModelImpl;
import jee.boot.entity.task.IExportField;
import jee.boot.entity.task.IExportModel;
import jee.boot.entity.task.AbstractGeneralTemplateExportService;
import jee.boot.entity.auth.standard.DataValue;
import jee.boot.oauth.standard.service.StandardModelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StandardModelExport implements AbstractGeneralTemplateExportService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private StandardModelService standardModelService;
    @Autowired
    private AccountHandler accountHandler;
    @Autowired
    private AuthorityHandler authorityHandler;
    @Autowired
    private RemoteEndpoint remoteEndpoint;
    @Autowired
    private ProjectConfig projectConfig;
    /**
     * 根据task查询当前导出任务需要的数据,
     *
     * @param task 当前任务
     * @return 返回数据约束为Map类型
     */
    @Override
    public Map<String, Object> queryData(IexpTask task) {
        Map<String, Object> map = new HashMap<>();
        String jsonParam = task.getJsonParam();
        StandardModel standardModel = new StandardModel();
        if (StringUtils.isNotBlank(jsonParam)) {
            try {
                standardModel = JsonMapper.fromJsonString(jsonParam, StandardModel.class);
            } catch (Exception e) {
                logger.warn("解析参数失败,使用默认参数", e);
            }
        }
        Page<Map<String, DataValue>> page = standardModelService.findPage(standardModel);
        map.put("list", page.getList());
        return map;
    }

    @Override
    public IexpTaskConfig taskConfig(IexpTask task) {
        IexpTaskConfig config = new IexpTaskConfig();
        String jsonParam = task.getJsonParam();
        StandardModel standardModel = new StandardModel();
        if (StringUtils.isNotBlank(jsonParam)) {
            try {
                standardModel = JsonMapper.fromJsonString(jsonParam, StandardModel.class);
            } catch (Exception e) {
                logger.warn("解析参数失败,使用默认参数", e);
            }
        }
        IExportModel exportModel=getExportModel(standardModel);
        config.initExportByModelConfig(exportModel,exportModel.getTitle());
        return config;
    }
    /**
     * 从当前用户的权限配置中读取模型配置数据,找到需要导出的列配置
     * @param standardModel
     * @return
     */
    private IExportModel getExportModel_bak(StandardModel standardModel){
        ExportModelImpl exportModel=new ExportModelImpl();
        ModelData modelData = standardModel.getModelData();
        exportModel.setTitle(modelData.getName());
        User currentUser = (User)authorityHandler.getCurrentUser();
        List<AuthEntity> modelAuthList = currentUser.getModelAuthList();
        if(modelAuthList!=null &&!modelAuthList.isEmpty()){
            ModelData authModel=null;
            for(AuthEntity authEntity:modelAuthList){
                if(StringUtils.equals(((ModelData)authEntity.getEntity()).getCode(),modelData.getCode())){
                    authModel=(ModelData)authEntity.getEntity();
                    break;
                }
            }
            if(authModel!=null){
                List<AuthEntity> columnAuthList = authModel.getColumnAuthList();
                if(columnAuthList!=null && columnAuthList.isEmpty()){
                    List<Column> columnList = columnAuthList.stream().map(d -> (Column) d.getEntity()).collect(Collectors.toList());
                    if(columnList!=null && !columnList.isEmpty()){
                        List<IExportField> fieldList= Lists.newArrayList();
                        columnList.stream().forEach(column -> {
                            fieldList.add(new IExportField() {
                                @Override
                                public String getTitle() {
                                    return column.getName();
                                }

                                @Override
                                public String getFieldName() {
                                    return column.getCode();
                                }

                                @Override
                                public Class<?> getFieldType() {
                                    return null;
                                }

                                @Override
                                public String getDictType() {
                                    // 字典类型
                                    if(StringUtils.equals("DIC_SYS_DataDomainType_DDT01",column.getDataDomainType())){
                                        return column.getDataDomain();
                                    }
                                    return null;
                                }

                                @Override
                                public String getDictField() {
                                    return null;
                                }

                                @Override
                                public String getFormat() {
                                    return null;
                                }
                            });
                        });
                        exportModel.setExportFieldList(fieldList);
                    }

                }
            }
        }
        return exportModel;
    }
    /**
     * 从当前用户的权限配置中读取模型配置数据,找到需要导出的列配置
     * @param standardModel
     * @return
     */
    private IExportModel getExportModel(StandardModel standardModel){
        ExportModelImpl exportModel=new ExportModelImpl();
        String json = standardModel.getExportJson();
        Map<String,Object> exportMap = JsonMapper.fromJsonString(json,Map.class);
        String title = getValue(exportMap,"title");
        List<Map<String,Object>> exportFieldList=getValue(exportMap,"exportFieldList");
        exportModel.setTitle(title);
        List<IExportField> fieldList= Lists.newArrayList();
        if(exportFieldList!=null && !exportFieldList.isEmpty()){
            exportFieldList.forEach(field->{
                ;
                fieldList.add(new IExportField() {
                    @Override
                    public String getTitle() {
                        return getValue(field,"title");
                    }

                    @Override
                    public String getFieldName() {
                        return getValue(field,"fieldName")+".v";
                    }

                    @Override
                    public Class<?> getFieldType() {
                        return null;
                    }

                    @Override
                    public String getDictType() {
                        // 字典类型
                        return getValue(field,"dictType");
                    }

                    @Override
                    public String getDictField() {
                        return null;
                    }

                    @Override
                    public String getFormat() {
                        return getValue(field,"format");
                    }
                });
            });
        }
        exportModel.setExportFieldList(fieldList);
        return exportModel;
    }
    private <T> T getValue(Map<String,Object> map,String key){
        if(map!=null&& map.containsKey(key)){
            return (T)map.get(key);
        }
        return null;
    }

}
